<?php
if ( ! defined('__TYPECHO_ROOT_DIR__'))
{
    exit;
}

$path_delimiter = (strpos(__FILE__, ':') !== false) ? ';' : ':';
ini_set(
        'include_path',
        ini_get('include_path') . $path_delimiter . dirname(__FILE__) . '/PEAR');

require_once 'HTTP/Request.php';

define('YUPOO_UPLOAD_API', 'http://www.yupoo.com/api/upload/');
define('YUPOO_REST_API', 'http://www.yupoo.com/api/rest/');

class Tyupoo
{
    private $api_key    = '';
    private $secret     = '';
    private $req        = null;
	private $token		= '';

    public function __construct($api_key, $secret, $token)
    {
        $this->api_key = $api_key;
        $this->secret  = $secret;
		$this->token   = $token;

        $this->req = new HTTP_Request('', array('timeout'=>1.5));
        $this->req->setMethod(HTTP_REQUEST_METHOD_POST);
		//$this->req->setProxy('127.0.0.1', 8888);
    }

    public function upload($photo, $content_type = null, $album_id = '', $title = '', $description = '', $tags = '', $is_public = 1)
    {
        $args = array(
			'album_id' 		=> $album_id,
			'title'			=> $title,
			'description' 	=> $description,
			'tags' 			=> $tags,
			'is_public'		=> $is_public,
			'api_key'		=> $this->api_key,
			'auth_token'	=> $this->token,
        );
		$sign = $this->getSign($args);
		$args['api_sig'] = $sign;
		$req = $this->getReq(YUPOO_UPLOAD_API, $args);
        $photo = realpath($photo);
		if ($content_type)
		{
			$req->addFile('photo', $photo, $content_type);
		}
        else
		{
			$req->addFile('photo', $photo);
		}
		$res = $req->sendRequest();
		$result = $req->getResponseBody();
		$xml = simplexml_load_string($result);
		$result = $this->objToArray($xml);
		$photos = array();
		if ( ! empty($result['err']))
		{
			$this->handleErr($result);
			return null;
		}
		else
		{
			$photos[] = $result['photos']['photo']['@attributes'];
		}
		return $photos;
    }

	public function getAlbumList($userid)
	{
		$args = array(
			'method' => 'yupoo.albums.getList',
			'api_key' => $this->api_key,
			'user_id' => $userid,
		);
		$ret = $this->reqRest($args);
		$albumList = array();
		if ( ! empty($ret['err']))
		{
			$this->handleErr($ret);
			return null;
		}
		else
		{
			$albums = $ret['albums']['album'];
			foreach ($albums as $album)
			{
				$albumList[] = array(
					'id' 		=> $album['@attributes']['id'],
					'photos'	=> $album['@attributes']['photos'],
					'title'		=> $album['title'],
				);
			}
		}
		return $albumList;
	}

	public function getPhotos($albumid/*, $page = 1, $per_page = 8*/)
	{
		$args = array(
			'method' => 'yupoo.albums.getPhotos',
			'api_key' => $this->api_key,
			'album_id' => $albumid,
		);
		$ret = $this->reqRest($args);
		$photoList = array();
		if ( ! empty($ret['err']))
		{
			$this->handleErr($ret);
			return null;
		}
		else
		{
			$photos = $ret['album']['photos']['photo'];
			if(!empty($photos['@attributes']))
			{
				//只有一张照片
				$photos = array($photos);
			}
			foreach ($photos as $photo)
			{
				$photoList[] = $photo['@attributes'];
			}
		}
		return $photoList;
	}

	public function getNotInAlbum($page = 1, $per_page = 100)
	{
		$args = array(
			'method' => 'yupoo.photos.getNotInAlbum',
			'api_key' => $this->api_key,
			'auth_token' => $this->token,
			'page' => $page,
			'per_page' => $per_page,
		);
		$this->signArgs($args);
		$ret = $this->reqRest($args);
		$photoList = array();
		if ( ! empty($ret['err']))
		{
			$this->handleErr($ret);
			return null;
		}
		else
		{
			$photos = $ret['result']['photos']['photo'];
			foreach ($photos as $photo)
			{
				$photoList[] = $photo['@attributes'];
			}
		}
		return $photoList;
	}

	public function getTokenInfo($frob)
	{
		$args = array(
			'method' 	=> 'yupoo.auth.getToken',
			'api_key' 	=> $this->api_key,
			'frob'		=> $frob,
		);
		$sign = $this->getSign($args);
		$args['api_sig'] = $sign;
		$info = $this->reqRest($args);
		return $info;
	}

	public function getFrob()
	{
		$args = array(
			'method' 	=> 'yupoo.auth.getFrob',
			'api_key' 	=> $this->api_key,
		);
		$sign = $this->getSign($args);
		$args['api_sig'] = $sign;
		$result = $this->reqRest($args);
		if ( ! empty($result['err']))
		{
			$frob = ($result['err']['@attributes']['code'] == 0) ? null : '';
		}
		else
		{
			$frob = $result['frob'];
		}
		return $frob;
	}

	public function getAuthUrl($frob)
	{
		$args = array(
			'api_key'   => $this->api_key,
			'frob' 		=> $frob,
			'perms'		=> 'write',
		);
		$sign = $this->getSign($args);
		$url = "http://www.yupoo.com/services/auth/?api_key={$args['api_key']}&frob={$frob}&perms={$args['perms']}&api_sig={$sign}";
		return $url;
	}

    private function getReq($url, $args = array())
    {
        $this->req->clearPostData();
        $this->req->setURL($url);
		foreach ($args as $name => $value)
		{
			if ( ! empty($args[$name]))
			{
				$this->req->addPostData($name, $value);
			}
		}
        return $this->req;
    }

	private function reqRest($args)
	{
		$req = $this->getReq(YUPOO_REST_API, $args);
		$res = $req->sendRequest();
		$result = $req->getResponseBody();
		if ( ! $result)
		{
			//ÍøÂç³ö´í
			$arr = array(
				'err' => array(
					'@attributes' => array(
						'code' => 0,
						'msg'  => 'connect failed',
					),
				),
			);
		}
		else
		{
			$xml = simplexml_load_string($result);
			$arr = $this->objToArray($xml);
		}
		return $arr;
	}

	private function signArgs(&$args)
	{
		ksort($args);
		$sign = array($this->secret);
		foreach($args as $key => $value)
		{
			if (empty($value))
			{
				continue;
			}
			$sign[] = $key . $value;
		}
		$sign = implode('', $sign);
		$sign = md5($sign);
		$args['api_sig'] = $sign;
		return $sign;
	}

	private function getSign($args)
	{
		$sign = $this->signArgs($args);
		return $sign;
		/*
		ksort($args);
		$sign = array($this->secret);
		foreach($args as $key => $value)
		{
			if (empty($value))
			{
				continue;
			}
			$sign[] = $key . $value;
		}
		$sign = implode('', $sign);
		$sign = md5($sign);
		return $sign;
		*/
	}

    private function objToArray($obj)
    {
        if (is_object($obj))
        {
            $array = get_object_vars($obj);
            foreach($array as $key => $val)
            {
                if (is_object($val))
                {
                    $array[$key] = $this->objToArray($val);
                }
                elseif (is_array($val))
                {
                    foreach($val as $k => $v)
                    {
                        if (is_object($v))
                        {
                            $array[$key][$k] = $this->objToArray($v);
                        }
                        else
                        {
                            $array[$key][$k] = $v;
                        }
                    }
                }
                else
                {
                    $array[$key] = $val;
                }
            }
            return $array;
        }
        return $obj;
    }

	public function getErrMsg($arr)
	{
		$err = $arr['err']['@attributes']['msg'];
		return $err;
	}

	public function getErrCode($arr)
	{
		$code = $arr['err']['@attributes']['code'];
		return $code;
	}

	private function handleErr($res)
	{

	}
}
?>